package com.betterjr.modules.flie.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.UserUtils;
import com.betterjr.modules.commission.entity.CommissionRecord;
import com.betterjr.modules.document.entity.CustFileItem;
import com.betterjr.modules.document.service.DataStoreService;

@Service
public class TxtsFileService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private DataStoreService dataStoreService; // 将文件转成输入流

    /**
     * 
     * @Title: transformXLSFileToTxt 
     * @Description: TODO(生成txt文档) 
     * @param @param recordList
     * @param @param anFileName
     * @param @return
     * @param @throws Exception 参数说明 
     * @return CustFileItem 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月2日 上午10:26:57
     */
    public CustFileItem transformXLSFileToTxt(List<CommissionRecord> recordList, String anFileName) throws Exception {
        logger.info("文件导出服务： 操作人：" + UserUtils.getOperatorInfo().getName());
        BTAssert.notNull(recordList, "数据记录不存在");
        final StringBuffer recordData = new StringBuffer();
        // 把要生成文件的数据读取到StringBuffer中
        for (final CommissionRecord record : recordList) {
            recordData.append(
                    record.getBankAccount() + "|" + record.getBankAccountName() + "|" + record.getBankPayCode() + "|"
                            + "个人帐户" + "|" + record.getBalance() + "|" + "劳务费" + "|" + record.getRefNo() + "\r\n");
        }
        // 把数据读取到输入流中
        InputStream is = null;
        try {
            is = new ByteArrayInputStream(recordData.toString().getBytes("UTF-8"));
        }
        catch (final IOException e) {
            logger.info("数据流读入出错!" + e.getMessage());
        }
        // 生成文件记录
        final CustFileItem item = dataStoreService.saveStreamToStore(is, "other", anFileName);
        logger.info("导出文件生成成功：" + UserUtils.getOperatorInfo().getName());
        is.close();
        return item;
    }
}
